// Created by wangliang on 2025/2/14.
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_demo/pages/image/image_picker_page_view_model.dart';
import 'package:flutter_app_demo/pages/image/image_view_page_view_model.dart';
import 'package:go_router/go_router.dart';
import 'package:mvvm_plus/mvvm_plus.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

class ImageViewPage extends ViewWidget<ImageViewPageViewModel> {
  final List<String> uris;
  final int initialPage;

  ImageViewPage({super.key, required this.uris, this.initialPage = 0})
      : super(
          builder: () => ImageViewPageViewModel(
            uris: uris,
            initialPage: initialPage,
          ),
        );

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          child: PhotoViewGallery.builder(
            itemCount: viewModel.uris.length,
            builder: (context, index) {
              return PhotoViewGalleryPageOptions(
                  imageProvider: _getImageProvider(viewModel.uris[index]),
                  minScale: PhotoViewComputedScale.contained,
                  onTapUp: (context, details, value) {
                    context.pop();
                  },
                  maxScale: PhotoViewComputedScale.covered);
            },
            loadingBuilder: (context, event) => Center(
              child: Container(
                width: 20.0,
                height: 20.0,
                child: CircularProgressIndicator(
                  value: event == null
                      ? 0
                      : event.cumulativeBytesLoaded / event.expectedTotalBytes!,
                ),
              ),
            ),
            pageController: viewModel.pageController,
          ),
        ),
      ],
    );
  }

  ImageProvider _getImageProvider(String uri) {
    if (uri.startsWith("http")) {
      return CachedNetworkImageProvider(uri);
    } else {
      return FileImage(File(uri));
    }
  }
}
